import { useEffect } from "react";
import { useModel } from "umi";
import { v4 as uuidv4 } from "uuid";
import { Form, Input, Button, Cascader, message, Space, Upload, Modal, Row, Col } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { useReactive } from "ahooks";

const CreateCommodityModal = ({ reloadData }) => {
    const { onCloseGlobalModal } = useModel("global.modal", (model) => model);
    const { remoteData, goipfs, transTree } = useModel("global", (model) => model);
    const { organizationUuid } = useModel("organization.info", (model) => model);
    const { baseInfo } = useModel("person.info", (model) => model);
    const [form] = Form.useForm();

    const state = useReactive({
        photoList: [],
        photos: {},
        submitLoading: false,
        selectedClass: [],
        treeCommodityClassData: [],
    });

    const loadTreeCommodityClass = async () => {
        state.treeCommodityClassData = transTree(
            [
                { ccUuid: 1, ccPaid: null, ccName: "一级分类" },
                { ccUuid: 2, ccPaid: 1, ccName: "二级分类" },
                { ccUuid: 3, ccPaid: null, ccName: "一级分类2" },
            ],
            "ccUuid",
            "ccPaid"
        );
    };

    useEffect(() => {
        loadTreeCommodityClass();
    }, []);

    const onFinish = async (values) => {
        if (state.photoList.length === 0) return message.warn("没有选择商品图片，请选择");
        state.submitLoading = true;
        const variables = {
            ...values,
            ciUuid: uuidv4(),
            ciAlna: values.ciBran + values.ciName + values.ciSpec,
            ciClna: state.selectedClass.map((item) => item.ccName).join("/"),
            ciClas: state.selectedClass || [],
            ciCrti: new Date().getUTCTime(),
            ciCpna: baseInfo.realName,
            ciCpid: baseInfo.uuid,
            ciUpti: new Date().getUTCTime(),
            ciUper: baseInfo.realName,
            ciUpid: baseInfo.uuid,
            ciPict: state.photoList.map((item) => item.path),
        };

        state.submitLoading = false;
    };

    //查看大图
    const onPreview = (file) => {
        state.photos = { previewImage: file.url, visible: true };
    };
    const handleCancel = () => {
        state.photos = { visible: false };
    };

    const ciNameValidator = async (rule, value) => {
        if (value && validates.titleAndName(value) && value.length < 51) {
            return Promise.resolve();
        } else {
            return Promise.reject("只能输入中文、英文、数字，最多50个字符");
        }
    };

    return (
        <div style={{ padding: "0 24px" }}>
            <Form form={form} layout="vertical" onFinish={onFinish}>
                <Form.Item label="商品名称" name="ciName" validateTrigger="onBlur" rules={[{ required: true, validator: ciNameValidator }]}>
                    <Input placeholder="请输入商品名称" />
                </Form.Item>

                <Form.Item label="品牌" name="ciBran" validateTrigger="onBlur" rules={[{ required: true }]}>
                    <Input placeholder="请输入品牌" />
                </Form.Item>

                <Form.Item label="规格型号" name="ciSpec" validateTrigger="onBlur" rules={[{ required: true }]}>
                    <Input placeholder="请输入规格型号" />
                </Form.Item>

                <Form.Item label="商品类别">
                    <Cascader
                        options={state.treeCommodityClassData}
                        placeholder="请选择商品类别"
                        changeOnSelect={false}
                        fieldNames={{ label: "ccName", value: "ccUuid" }}
                        onChange={(value, selectedOptions) => (state.selectedClass = selectedOptions)}
                    />
                </Form.Item>

                <Row gutter={20}>
                    <Col span={12}>
                        <Form.Item label="商品市场价" name="ciMava" validateTrigger="onBlur" rules={[{ required: true }]}>
                            <Input type={"number"} min="0" max="9999999" step="0.01" />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item label="商品计量单位" name="ciUnit" rules={[{ required: true }]}>
                            <Input placeholder="商品计量单位" />
                        </Form.Item>
                    </Col>
                </Row>

                <Form.Item label="商品描述" name="ciDesc">
                    <Input.TextArea rows={2} maxLength={250} placeholder="请输入商品描述" />
                </Form.Item>

                <Form.Item label="商品图片" rules={[{ required: true, message: "请上传图片，第一张图片默认为封面图片" }]}>
                    <Upload
                        multiple
                        listType="picture-card"
                        fileList={state.photoList}
                        beforeUpload={async (file, fileList) => {
                            const result = await goipfs.daemon.add(fs.readFileSync(file.path), { pin: false });
                            const photo = state.photoList.find((item) => item.path === result.path);
                            if (!photo) state.photoList = [...state.photoList, { url: goipfs.ipfsUrl + result.path, path: result.path, isNew: true }];
                            else message.warn("不能上传重复的图片，请重新选择图片");
                            return false;
                        }}
                        onRemove={(file) => {
                            if (file.isNew === false) state.hashUnpin.push(file.path);
                            state.photoList = state.photoList.filter((item) => item.url !== file.url);
                            return false;
                        }}
                        onPreview={onPreview}
                    >
                        <div>
                            <PlusOutlined />
                            <div style={{ marginTop: 8 }}>上传</div>
                        </div>
                    </Upload>
                </Form.Item>

                <div style={{ marginTop: 20, textAlign: "center" }}>
                    <Space>
                        <Button loading={state.submitLoading} type="primary" htmlType="submit" style={{ width: "100%" }}>
                            提交商品信息
                        </Button>
                        <Button loading={state.submitLoading} onClick={onCloseGlobalModal}>
                            取消
                        </Button>
                    </Space>
                </div>
            </Form>

            <Modal visible={state.photos.visible} footer={null} onCancel={handleCancel}>
                <img alt="加载" style={{ width: "100%", height: "100%" }} src={state.photos.previewImage} />
            </Modal>
        </div>
    );
};

export default CreateCommodityModal;
